<?php

namespace App\Services\Admin;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Services\Service;
use App\Models\User;
use App\Models\Role;
use App\Models\Dept;
use App\Models\Menu;


class UserService extends Service
{

    public static function options()
    {
        $list = User::query()->select('id', 'nickname');

        $list = $list->get()->toArray();

        $list = array_map(fn ($item) => [
            'value' => $item['id'],
            'label' => $item['nickname']
        ], $list);

        return $list;
    }

    public static function me(): array
    {

        $user = Auth::user();

        $data = [
            'userId'   => $user->id,
            'username' => $user->username,
            'nickname' => $user->nickname,
            'avatar'   => $user->avatar,
        ];

        $roles_query = Role::whereIn('id', $user->roleIds)->select('code', 'menuIds');

        $roles = $roles_query->pluck('code')->toArray();

        $data['roles'] = $roles;

        $menu_ids = $roles_query->pluck('menuIds')->toArray();
        $menu_ids = array_unique(array_merge(...$menu_ids));

        $menus_perm = Menu::whereIn('id', $menu_ids)->where('type', 4)->pluck('perm');

        $data['perms'] = $menus_perm->toArray();

        return $data;
    }

    public static function passwordReset($password, $id): array
    {

        $user = User::find($id);

        if (!$user) {
            self::throwValidationException('id', ['用户不存在']);
        }

        $user->update([
            'password' => Hash::make($password)
        ]);

        return [
            'id' => $user->id,
        ];
    }

    public static function index(array $params): array
    {

        $query = User::with('dept');

        $pageNum = $params['pageNum'];
        $pageSize = $params['pageSize'];


        if (!empty($params['keywords'])) {
            $keywords = $params['keywords'];

            $query->where(function ($q) use ($keywords) {
                $q->where('username', 'like', "%{$keywords}%")
                    ->orWhere('nickname', 'like', "%{$keywords}%")
                    ->orWhere('mobile', 'like', "%{$keywords}%");
            });
        }

        if (isset($params['deptId'])) {
            $deptId = $params['deptId'];

            $subDepts = Dept::getAllSubDepts($deptId);

            $query->whereIn('deptId', $subDepts->toArray());
        }

        if (isset($params['status'])) {


            $query->where('status', (int)$params['status']);
        }

        if (isset($params['createTime'])) {

            // 前端传入的一定是北京时间，数据库存的是 UTC 时间，所以关于时间的，一定要使用 self::parseDateRangeToUtc 转换之后再查，否则会相差 8 小时
            $start = self::parseDateRangeToUtc($params['createTime'][0]);
            $end   = self::parseDateRangeToUtc($params['createTime'][1]);

            $query->whereBetween('createTime', [$start, $end]);
        }

        $paginator = $query->paginate($pageSize, ['*'], 'page', $pageNum);

        $paginator->getCollection()->makeVisible(['createTime', 'updateTime']);

        $total = $paginator->total();

        $list = $paginator->getCollection()->map(function ($item) {
            $data = $item->toArray();
            $data['deptName'] = $item->dept ? $item->dept->name : null;
            unset($data['dept']);

            $roleNames = Role::whereIn('id', $data['roleIds'])->pluck('name')->toArray();

            $data['roleNames'] = implode(',', $roleNames);

            return $data;
        });

        return [
            'list'  => $list,
            'total' => $total,
        ];
    }

    public static function store(array $data): array
    {

        $user = User::create($data);

        return [
            'id' => $user->id,
        ];
    }

    public static function show(string $id): array
    {

        $user = User::select(['*'])->find($id);

        if (!$user) {
            self::throwValidationException('id', ['用户不存在']);
        }

        return $user->toArray();
    }


    public static function update(array $data, string $id): array
    {

        $user = User::find($id);

        if (!$user) {
            self::throwValidationException('id', ['用户不存在']);
        }

        $user->update($data);

        return [
            'id' => $user->id,
        ];
    }

    public static function destroy(string $id): array
    {

        $user = User::find($id);
        if (!$user) {
            self::throwValidationException('id', ['用户不存在']);
        }

        $user->delete();

        return [
            'id' => $user->id
        ];
    }
}
